<template>
  <a-spin :spinning="loading">
    <a-form v-bind="formItemLayout">
      <a-row>
        <a-col :span="24">
          <a-form-item label="风险事件名称" v-bind="validateInfos.riskEventName">
	          <a-textarea v-model:value="formData.riskEventName" :rows="4" placeholder="请输入风险事件名称" :disabled="disabled"/>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="所属装置" v-bind="validateInfos.riskDeviceId">
            <j-dict-select-tag v-model:value="formData.riskDeviceId" dictCode="tb_base_risk_device,name,id" placeholder="请选择所属装置" :disabled="disabled" @change="changeDeviceId"/>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="所属单元" v-bind="validateInfos.riskUnitId">
            <j-dict-select-tag v-model:value="formData.riskUnitId" :dictCode="argument.unitDictCode" placeholder="请选择所属单元" :disabled="argument.riskUnitFlag"/>
          </a-form-item>
        </a-col>
        
        <!-- <a-col :span="24">
          <a-form-item label="风险分析装置" v-bind="validateInfos.riskDeviceId">
	          <j-search-select v-model:value="formData.riskDeviceId" dict="tb_base_risk_device,name,id" :disabled="disabled" @change="changeDeviceId"/>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="风险分析单元" v-bind="validateInfos.riskUnitId" v-if="formData.riskDeviceId">
	          <j-search-select v-model:value="formData.riskUnitId" :dictCode="dictCodeList.unitDictCode" :disabled="disabled" />
          </a-form-item>
        </a-col> -->
        <a-col :span="24">
          <a-form-item label="重大危险源级别" v-bind="validateInfos.seriousHazard">
	          <j-dict-select-tag v-model:value="formData.seriousHazard" dictCode="serious_hazard" placeholder="请选择重大危险源级别" :disabled="disabled"/>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="责任部门" v-bind="validateInfos.hazardDep">
	          <j-select-dept v-model:value="formData.hazardDep" :multiple="true" checkStrictly :disabled="disabled" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="责任人" v-bind="validateInfos.hazardLiablePerson">
			  <j-select-user v-model:value="formData.hazardLiablePerson" :disabled="disabled"/>
          </a-form-item>
        </a-col>
        <!-- <a-col :span="24">
          <a-form-item label="删除标志" v-bind="validateInfos.deleted">
            <j-dict-select-tag type='radio' v-model:value="formData.deleted" dictCode="yn" placeholder="请选择删除标志" disabled/>
          </a-form-item>
        </a-col> -->
      </a-row>
    </a-form>

		<!-- 子表单区域 -->
    <a-tabs v-model:activeKey="activeKey" animated>
      <a-tab-pane tab="管控措施信息" key="tbBaseControlMeasures" :forceRender="true">
        <j-vxe-table
          :keep-source="true"
          resizable
          ref="tbBaseControlMeasuresTableRef"
          :loading="tbBaseControlMeasuresTable.loading"
          :columns="tbBaseControlMeasuresTable.columns"
          :dataSource="tbBaseControlMeasuresTable.dataSource"
          :height="340"
          :disabled="disabled"
          :rowNumber="true"
          :rowSelection="true"
          :toolbar="true"
          :linkageConfig="linkageConfig"/>
      </a-tab-pane>
    </a-tabs>
  </a-spin>
</template>

<script lang="ts">
  import { defineComponent, ref, reactive, computed, toRaw } from 'vue';
  import { useValidateAntFormAndTable } from '/@/hooks/system/useJvxeMethods';
  import { queryTbBaseControlMeasuresListByMainId, queryDataById, saveOrUpdate } from '../TbBaseRiskEvents.api';
  import { JVxeTable } from '/@/components/jeecg/JVxeTable';
  import {tbBaseControlMeasuresColumns} from '../TbBaseRiskEvents.data';
  import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';
  import JSearchSelect from '/@/components/Form/src/jeecg/components/JSearchSelect.vue';
  import JSelectDept from '/@/components/Form/src/jeecg/components/JSelectDept.vue';
  import JSelectUser from '/@/components/Form/src/jeecg/components/JSelectUser.vue';
  import { Form } from 'ant-design-vue';
  import { defHttp } from '/@/utils/http/axios';
  import { JVxeLinkageConfig } from '/@/components/jeecg/JVxeTable/types';
  const useForm = Form.useForm;

  export default defineComponent({
    name: "TbBaseRiskEventsForm",
    components:{
      JDictSelectTag,
      JSearchSelect,
      JSelectDept,
      JSelectUser,
      JVxeTable,
    },
    props:{
      formDisabled:{
        type: Boolean,
        default: false
      },
      formData: { type: Object, default: ()=>{} },
      formBpm: { type: Boolean, default: true }
    },
    emits:['success'],
    setup(props, {emit}) {
      const loading = ref(false);
      const tbBaseControlMeasuresTableRef = ref();
      const tbBaseControlMeasuresTable = reactive<Record<string, any>>({
        loading: false,
        columns: tbBaseControlMeasuresColumns,
        dataSource: []
      });
      const activeKey = ref('tbBaseControlMeasures');
      const formData = reactive<Record<string, any>>({
        id: '',
        riskEventName: '',   
        riskDeviceId: '',   
        riskUnitId: '',   
        seriousHazard: '',   
        hazardDep: '',   
        hazardLiablePerson: '',   
        deleted: '',   
      });
      // 联动配置
      const linkageConfig = ref<JVxeLinkageConfig[]>([
        // 可配置多个联动
        { requestData: requestClassify1, key: 'classify1' },
        //{ requestData: requestClassify2, key: 'classify2' },
      ]);

      //表单验证
      const validatorRules = reactive({
        riskEventName: [{ required: true, message: '请输入风险事件名称!'},],
        riskDeviceId: [{ required: true, message: '请输入风险分析装置!'},],
        riskUnitId: [{ required: true, message: '请输入风险分析单元!'},],
        seriousHazard: [{ required: true, message: '请输入重大危险源级别!'},],
        hazardDep: [{ required: true, message: '请输入责任部门!'},],
      });
      const {resetFields, validate, validateInfos} = useForm(formData, validatorRules, {immediate: false});
      const dbData = {};
      const formItemLayout = {
        labelCol: {xs: {span: 24}, sm: {span: 5}},
        wrapperCol: {xs: {span: 24}, sm: {span: 16}},
      };
      // const dictCodeList = reactive({
      //   unitDictCode: "tb_base_risk_unit,risk_unit_name,id"
      // })
      const argument = reactive({
        unitDictCode: "tb_base_risk_unit,risk_unit_name,id",
        riskUnitFlag: true
      })

      // 表单禁用
      const disabled = computed(()=>{
        if(props.formBpm === true){
          if(props.formData.disabled === false){
            return false;
          }else{
            return true;
          }
        }
        return props.formDisabled;
      });

     

      /** 查询后台真实数据 */
      async function requestClassify1(parent) {
        let result;
        // 如果parent为空，则查询第一级菜单
        console.log("requestClassify1-------------------------", parent);
        if (parent === '') {
          result = await defHttp.get({
            url: '/TbBaseControlMeasuresType/tbBaseControlMeasuresType/loadTreeRoot',
            params: {async:true,pcode:parent},
          });
        } else {
          result = await defHttp.get({
            url: '/TbBaseControlMeasuresType/tbBaseControlMeasuresType/loadTreeChildren',
            params: { pid: parent },
          });
        }
        // 返回的数据里必须包含 value 和 text 字段
        return result.map((item) => ({ value: item.key, text: item.title }));
      }

      /** 查询后台真实数据 */
      // async function requestClassify2(parent) {
      //   let result;
      //   console.log("requestClassify2-------------------------", parent);
      //   // 如果parent为空，则查询第一级菜单
      //   console.log("parent-------------------------", parent);
      //   if (parent !== '') {
      //     result = await defHttp.get({
      //       url: '/TbBaseControlMeasuresType/tbBaseControlMeasuresType/loadTreeChildren',
      //       params: { pid: parent },
      //     });
      //   }
      //   // 返回的数据里必须包含 value 和 text 字段
      //   return result.map((item) => ({ value: item.key, text: item.title }));
      // }

      function add() {
        resetFields();
        tbBaseControlMeasuresTable.dataSource = [];
      }

      async function edit(row) {
        //主表数据
        await queryMainData(row.id);
        //子表数据
        const tbBaseControlMeasuresDataList = await queryTbBaseControlMeasuresListByMainId(row['id']);
        tbBaseControlMeasuresTable.dataSource = [...tbBaseControlMeasuresDataList];
      }

      async function queryMainData(id) {
        const row = await queryDataById(id);
        const tmpData = {};
        Object.keys(formData).forEach((key) => {
          if(row.hasOwnProperty(key)){
            tmpData[key] = row[key]
          }
        })
        //赋值
        Object.assign(formData,tmpData);
      }

      const {getSubFormAndTableData, transformData} = useValidateAntFormAndTable(activeKey, {
        'tbBaseControlMeasures': tbBaseControlMeasuresTableRef,
      });

      async function getFormData() {
        await validate();
        return transformData(toRaw(formData))
      }

      async function submitForm() {
        const mainData = await getFormData();
        const subData = await getSubFormAndTableData();
        const values = Object.assign({}, dbData, mainData, subData);
        console.log('表单提交数据', values)
        const isUpdate = values.id ? true : false
        await saveOrUpdate(values, isUpdate);
        //关闭弹窗
        emit('success');
      }
      
      function setFieldsValue(values) {
        if(values){
          Object.keys(values).map(k=>{
            formData[k] = values[k];
          });
        }
      }

      /**
       * 值改变事件触发-树控件回调
       * @param key
       * @param value
       */
      function handleFormChange(key, value) {
        formData[key] = value;
      }
      
      function changeDeviceId(id) {
        if(id){
          formData.riskUnitId = null;
          argument.riskUnitFlag = false;
        }else{
          argument.riskUnitFlag = true;
        }
        argument.unitDictCode = "tb_base_risk_unit,risk_unit_name,id,device_id="+id
      }

      // function changeDeviceId(id) {
      //   dictCodeList.unitDictCode = "tb_base_risk_unit,risk_unit_name,id,device_id='"+id+"'";
      //   console.log("dictCodeList.unitDictCode-------------------------"+ dictCodeList.unitDictCode);
      // }

      return {
        tbBaseControlMeasuresTableRef,
        tbBaseControlMeasuresTable,
        validatorRules,
        validateInfos,
        activeKey,
        loading,
        formData,
        setFieldsValue,
        handleFormChange,
        formItemLayout,
        disabled,
        getFormData,
        submitForm,
        add,
        edit,
        changeDeviceId,
        argument,
        linkageConfig
      }
    }
  });
</script>
